package main

import (
	"fmt"
	"time"
)

func t_pipeline1() {
	naturals := make(chan int)
	squares := make(chan int)

	//产生数字的goroutine
	go func() {
		for x:=0; ;x++ {
			naturals <- x
		}
	}()

	//把数字平方化的goroutine
	go func() {
		for {
			x := <-naturals
			squares <- x*x
		}
	}()

	//打印结果的main goroutine
	for {
		fmt.Println(<-squares)
		time.Sleep(1 * time.Second)
	}
}

//t_pipeline1 传递无穷多个数，如果想传递有限个，就需告诉接收者
//满足一定条件就不需等待了
func t_pipeline2() {
	naturals := make(chan int)
	squares := make(chan int)

	//产生数字的goroutine
	go func() {
		for x:=0; x<100 ;x++ {
			naturals <- x
		}
		close(naturals)
	}()

	//把数字平方化的goroutine
	go func() {
		for x:= range naturals {
			squares <- x*x
		}
		close(naturals)
	}()

	//打印结果的main goroutine
	for {
		fmt.Println(<-squares)
		time.Sleep(300 * time.Millisecond)
	}
}


func counter(out chan<- int) {
	for x:=0; x<10; x++ {
		out <- x
	}
	close(out)
}
func squarer(out chan<- int, in <-chan int) {
	defer close(out)
	for v:= range in {
		out <- v*v
	}
}
func printer(in <- chan int) {
	for v:= range in {
		fmt.Println(v)
	}
}

func t_pipeline3() {
	naturals := make(chan int)
	squares := make(chan int)
	go counter(naturals)
	go squarer(squares,naturals)
	printer(squares)
}

func main() {
	t_pipeline3()
}
